Page({
  data: {
    selectedBoat: {
      id: '',
      boatNumber: ''
    },
    selectedRecord: {
      id: '',
      location: '',
      fishingTime: '',
      quantity: '',
      species: ''
    },
    qrcodeUrl: ''
  },

  onLoad() {
    this.loadBoats();
  },

  loadBoats() {
    wx.request({
      url: 'https://api.example.com/boats',
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            boats: res.data
          });
        } else {
          wx.showToast({
            title: '获取渔船列表失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  selectBoat() {
    const { boats } = this.data;
    wx.showActionSheet({
      itemList: boats.map(boat => boat.boatNumber),
      success: (res) => {
        const selectedBoat = boats[res.tapIndex];
        this.setData({
          selectedBoat
        });
        this.loadRecords(selectedBoat.id);
      }
    });
  },

  loadRecords(boatId) {
    wx.request({
      url: `https://api.example.com/fishing-records?boatId=${boatId}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            records: res.data
          });
        } else {
          wx.showToast({
            title: '获取捕捞记录失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  selectRecord() {
    const { records } = this.data;
    wx.showActionSheet({
      itemList: records.map(record => `${record.location} - ${record.fishingTime}`),
      success: (res) => {
        const selectedRecord = records[res.tapIndex];
        this.setData({
          selectedRecord
        });
      }
    });
  },

  generate() {
    const { selectedBoat, selectedRecord } = this.data;
    if (!selectedBoat.id || !selectedRecord.id) {
      wx.showToast({
        title: '请选择渔船和捕捞记录',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'https://api.example.com/qrcode/generate',
      method: 'POST',
      data: {
        boatId: selectedBoat.id,
        recordId: selectedRecord.id
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            qrcodeUrl: res.data.qrcodeUrl
          });
        } else {
          wx.showToast({
            title: '生成二维码失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  goBack() {
    wx.navigateBack();
  }
}); 